import React, { useState, useRef, useEffect } from 'react';
import { Space, Table, Tag, Modal, Button, message } from 'antd';
import { AudioOutlined } from '@ant-design/icons';
import { Input } from 'antd';
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'
import { gethazard, deletehazard, edithazard, addhazard } from '@/api/hazard'
import Userfrom from '@/components/userfrom3/index'
const Fieldmanagement = () => {
  const { Search } = Input;
  const [messageApi, contextHolder] = message.useMessage();

  const [size, setSize] = useState('large'); // default is 'middle'
  const { confirm } = Modal
  const [userdata, setUser] = useState([])
  const [Searchdata, setSearch] = useState([])
  const [deletedata, setdeleteUser] = useState([])
  const [editdata, seteditUser] = useState([])
  const [editid, seteditUserID] = useState([])
  const [adddata, setaddUser] = useState([])
  // 
  const [dataSource, setdataSource] = useState([])
  const [isAddVisible, setisAddVisible] = useState(false)
  const [isUpdateVisible, setisUpdateVisible] = useState(false)
  const [roleList, setroleList] = useState([])
  const [regionList, setregionList] = useState([])
  const [current, setcurrent] = useState(null)

  const [isUpdateDisabled, setisUpdateDisabled] = useState(false)
  const AddForm = useRef(null)
  const UpdateForm = useRef(null)
  const getdata = async () => {
    let { data: { users } } = await gethazard();
    console.log(users);
    // console.log(users);
    setUser(users)
  }
  useEffect(() => {
    getdata()
  }, [])
  const showinfo = (item) => {
    // console.log(item);
    // setinfo(item)
    // setTimeout(() => {
    // setinfoVisible(true)
    //   console.log(UpdateForm);
    //   // UpdateForm.current.setFieldsValue(item);
    // }, 100);
  }


  const confirmMethod = (item) => {
    confirm({
      title: '你确定要删除?',
      icon: <ExclamationCircleOutlined />,
      // content: 'Some descriptions',
      onOk() {
        console.log(item);
        // console.log('OK');
        deleteMethod(item)
      },
      onCancel() {
        //   console.log('Cancel');
      },
    });
  }

  const deleteMethod = (item) => {
    const { id, role, patientindex } = item;
    // console.log(item);
    // if (index1.indexOf(patientindex) == -1) {
    deletehazard({ id }).then(res => {
      message.success("删除成功")
      getdata()
    })
    // } else {
    //     message.error("病情严重，需院方及亲人同意")
    // }
    // console.log(item)
    // 当前页面同步状态 + 后端同步
    // console.log(dataSource);
    // var a = setdataSource(dataSource.filter(data => data.id !== item.id))
    // console.log(a);
    // axios.delete(`/users/${item.id}`)
  }

  let opertateFormLabel = [

    {
      model: "id",
      label: "id",
      type: "input",
    },
    {
      model: "title",
      label: "管理员",
      type: "input",
      
    },
    {
      model: "Video_quality_settings1",
      label: "直播分辨率",
      type: "input",
    },
    {
      model: "Interactive_feature_settings1",
      label: "互动功能",
      type: "input",
    },
    {
      model: "live_recording1",
      label: "直播录制方法",
      type: "input",
    },
    // {
    //   model: "IP",
    //   label: "IP",
    //   type: "input",
    // },

    {
      model: "birth",
      label: "修改时间",
      type: "date",
    },
    {
      model: "birth",
      label: "新增时间",
      type: "date",
    },
  ]

  const handleUpdate = (item) => {
    setisUpdateVisible(true)
    // console.log(item);
    setTimeout(() => {
      const { birth, id } = item;
      item.birth = dayjs(birth);
      setregionList(opertateFormLabel);
      seteditUserID(id)
      UpdateForm.current.setFieldsValue(item);
    }, 100)
    // console.log("dsgsgsgs", UpdateForm);

    setcurrent(item)
  }

  const addFormOK = () => {
    AddForm.current.validateFields().then(value => {
      const { birth } = value;
      value.birth = birth.format('YYYY-MM-DD');
      if (userdata.map(v => v.title).indexOf(value.title) != -1) {
        message.error("用户名已存在")
      } else {
        value.id = ++userdata.length
        setisAddVisible(false)
        AddForm.current.resetFields()
        addhazard(value).then((response) => {
          message.success("添加成功!")
          getdata()
        }).catch(e => {
          message.success("添加失败,请重试!")
        })

      }
    }).catch(err => {
      // console.log(err)
    })
  }

  const updateFormOK = () => {
    // console.log(item);
    var a = UpdateForm.current.validateFields().then(value => {
      value.birth = value.birth.format('YYYY-MM-DD');
      var b = userdata.map(v => v.title).indexOf(value.title);
      // console.log(b);
      // var userid = userdata[b].id
      // console.log(userid);
      value.id = editid;
      // console.log(editid);
      // console.log(userdata);
      console.log(value);
      // var userid = value.title;

      // var b = userdata.filter(v=> v.map(v.title)=value.title)

      edithazard(value).then((response) => {
        // console.log(value);
        // console.log(response);

        getdata()
        message.success('修改成功！')
      }).catch(e => {
        message.error('修改失败！')
        // message.success("编辑失败,请重试!")
      })
      setisUpdateVisible(false)

      setdataSource(dataSource.map(item => {
        if (item.id === current.id) {
          return {
            ...item,
            ...value,
            role: roleList.filter(data => data.id === value.roleId)[0]
          }
        }
        return item
      }))
      setisUpdateDisabled(!isUpdateDisabled)


      // }

    })
  }
  const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '管理员',
      dataIndex: 'title',
      key: 'title',
      render: (text) => <h3>{text}</h3>,
    },
    {
      title: '直播分辨率',
      dataIndex: 'Video_quality_settings1',
      key: 'Video_quality_settings1',
    },  
    {
      title: '互动功能',
      dataIndex: 'Interactive_feature_settings1',
      key: 'Interactive_feature_settings1',
    },  
    {
      title: '直播录制方法',
      dataIndex: 'live_recording1',
      key: 'live_recording1',
    },  

    // {
    //   title: 'IP属地',
    //   dataIndex: 'address',
    //   key: 'address',
    // },
    // {
    //   title: '网站域名',
    //   dataIndex: 'url',
    //   key: 'url',
    // },
    // {
    //   title: 'IP',
    //   dataIndex: 'IP',
    //   key: 'IP',
    // },
    // {
    //   title: '系统类型',
    //   dataIndex: 'systematic1',
    //   key: 'systematic1',
    // },
    // {
    //   title: '内存',
    //   dataIndex: 'memory',
    //   key: 'memory',
    //   render: (text) => <h3>{text} GiB</h3>,
    // },
    // {
    //   title: 'vCPU',
    //   dataIndex: 'vCPU',
    //   key: 'vCPU',
    //   render: (text) => <h3>{text} </h3>,
    // },
    // {
    //   title: '处理器',
    //   dataIndex: 'processorlist1',
    //   key: 'processorlist1',
    // },
    // {
    //   title: '采集天气种类',
    //   dataIndex: 'patient1',
    //   key: 'patient1',
    // },
    {
      title: '新增时间',
      dataIndex: 'birth',
      key: 'birth',
    },
    {
      title: '修改时间',
      dataIndex: 'birth',
      key: 'birth',
    },
    {
      title: "操作",
      render: (item) => {
        return <div>
        <Button danger  icon={<DeleteOutlined />} onClick={() => confirmMethod(item)}>删除</Button>
        <Button type="primary" icon={<EditOutlined />} disabled={item.default} onClick={() => handleUpdate(item)} >修改</Button>
      </div>
      }
    }
  ]

  const handleUpdate2 = () => {
    setisAddVisible(true)
    setregionList(opertateFormLabel);
  }
  return (
    <div>
      <Button onClick={() => {
        handleUpdate2()
      }} type="primary" size={size}>新增</Button>
      <Table columns={columns} dataSource={userdata}
        pagination={{
          pageSize: 6
        }}
        rowKey={item => item.id} />
      <Modal
        open={isUpdateVisible}
        title="更新用户"
        okText="更新"
        cancelText="取消"
        onCancel={() => {
          setisUpdateVisible(false)
          setisUpdateDisabled(!isUpdateDisabled)
        }}
        onOk={() => updateFormOK()}
      >
        <Userfrom regionList={regionList} roleList={roleList} ref={UpdateForm} isUpdateDisabled={isUpdateDisabled} isUpdate={true}></Userfrom>
      </Modal>
      <Modal
        open={isAddVisible}
        title="添加用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setisAddVisible(false)
        }}
        onOk={() => addFormOK()}
      >
        <Userfrom regionList={regionList} roleList={roleList} ref={AddForm}></Userfrom>
      </Modal>
    </div>
  )
}

export default Fieldmanagement